import cv2
import numpy as np
if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread("C:\\Users\\20436\Desktop\\xingxing.jpg")

    # 2. 灰度化
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)

    # 3. 二值化
    _, image_np_thresh = cv2.threshold(
        image_np_gray,
        75,
        255,
        cv2.THRESH_BINARY
    )

    # 4. 查找轮廓
    contours, hierarchy = cv2.findContours(
        image_np_thresh,
        cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE
    )



    # 5. 外界轮廓
    contour_image = image_np.copy()
    def colors(i):
        b=i*134%255
        g=i*183%255
        r=i*217%255
        return(b,g,r)
    # 遍历轮廓
    for i,cnt in zip(range(len(contours)),contours) :
        # 计算最小外接圆
        # 返回值：圆心和半径
        rect = cv2.minAreaRect(cnt)
        points = cv2.boxPoints(rect)

        # 转整形
        points =  np.int32(points)

        # 画矩形
        cv2.drawContours(
            contour_image,# 在哪里画
            [points ],
            -1,
            colors(i),  # 颜色
            2,  # 粗度
            cv2.LINE_AA  # 抗锯齿
        )

    # 6. 图片输出
    cv2.imshow('image_np_thresh', image_np_thresh)
    cv2.imshow('image_np_gray', image_np_gray)
    cv2.imshow('contour_image', contour_image)
    cv2.imwrite('contour_image.jpg',contour_image)
    cv2.waitKey(0)